import 'dart:convert';

import 'package:explore/my/person.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../navigation.dart';
import '../provider/person_info.dart';
import '../tool/pwdInput.dart';
import '../tool/textfield.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<StatefulWidget> createState() => _Login();
}

class _Login extends State<Login> {
  String account = '';
  String password = '';
  @override
  void initState() {
    super.initState();
    initPrefs();
  }

  Future<void> initPrefs() async {
    final person = Provider.of<PersonInfo>(context, listen: false);
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var accountStorage = prefs.getString('account');
    var passwordStorage = prefs.getString('password');
    if (accountStorage != null && passwordStorage != null) {
      final url = Uri.parse('http://127.0.0.1:5000/login');
      final headers = {'Content-Type': 'application/json;charset=utf-8'};
      final body = jsonEncode({
        'account': accountStorage,
        'password': passwordStorage,
      });
      final request = http.Request('get', url);
      request.headers.addAll(headers);
      request.body = body;
      final response = await request.send();
      final responseBody = await response.stream.bytesToString();
      var jsonData = jsonDecode(responseBody);
      if (response.statusCode == 200 && jsonData["code"] == "200") {
        person.changeAll(value: jsonData["msg"]);
        if (accountStorage != jsonData["msg"][1] ||
            passwordStorage != jsonData["msg"][3]) {
          return;
        }
        // ignore: use_build_context_synchronously
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (builder) {
          return const Navigation();
          // ignore: unnecessary_null_comparison
        }), (route) => route == null);
      }
    }
  }

  void setaccount(String newValue) {
    account = newValue;
  }

  void setPassword(String newValue) {
    password = newValue;
  }

  void loginButton(PersonInfo person) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    if (account == "" || password == "") {
      Fluttertoast.showToast(msg: '不能为空');
    }
    final url = Uri.parse('http://127.0.0.1:5000/login');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({
      'account': account,
      'password': password,
    });
    final request = http.Request('get', url);
    request.headers.addAll(headers);
    request.body = body;
    final response = await request.send();
    final responseBody = await response.stream.bytesToString();
    var jsonData = jsonDecode(responseBody);
    if (response.statusCode == 200 && jsonData["code"] == "200") {
      Fluttertoast.showToast(msg: '登录成功');
      person.changeAll(value: jsonData["msg"]);
      var info = jsonData["msg"].map((item) => item.toString()).toList();
      info = info.cast<String>().toList();
      await prefs.setString('account', jsonData["msg"][1]);
      await prefs.setString('password', jsonData["msg"][3]);
      // ignore: use_build_context_synchronously
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (builder) {
        return const Navigation();
        // ignore: unnecessary_null_comparison
      }), (route) => route == null);
    } else {
      Fluttertoast.showToast(msg: '账号密码错误');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Center(
              child: Container(
            width: 500,
            height: 380,
            margin: const EdgeInsets.only(left: 20, right: 20),
            padding: const EdgeInsets.all(20),
            color: const Color.fromARGB(109, 97, 86, 86),
            child: Column(
              children: [
                const Text(
                  "登录",
                  style: TextStyle(color: Colors.black, fontSize: 32),
                ),
                const SizedBox(height: 20),
                Textfield(
                  name: "用户名",
                  setVaule: setaccount,
                ),
                const SizedBox(height: 10),
                PwdInput(
                  name: "密码",
                  setVaule: setPassword,
                ),
                const SizedBox(height: 20),
                Consumer<PersonInfo>(builder: (ctx, person, child) {
                  return SizedBox(
                    width: 400,
                    height: 50,
                    child: ElevatedButton(
                      onPressed: () => loginButton(person),
                      child: const Text(
                        '确认',
                        style: TextStyle(fontSize: 24),
                      ),
                    ),
                  );
                }),
                const SizedBox(height: 20),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pushNamedAndRemoveUntil(
                        '/register', ModalRoute.withName('/'));
                  },
                  child: const Text(
                      textAlign: TextAlign.right,
                      "注册",
                      style: TextStyle(fontSize: 16, color: Colors.blue)),
                )
              ],
            ),
          ))),
    );
  }
}
